package com.hs.pre.search;

import static org.apache.solr.request.SolrParams.ROWS;
import static org.apache.solr.request.SolrParams.START;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.lucene.search.Query;
import org.apache.solr.core.SolrCore;
import org.apache.solr.request.QueryResponseWriter;
import org.apache.solr.request.SolrParams;
import org.apache.solr.request.SolrQueryResponse;
import org.apache.solr.request.XMLWriter;
import org.apache.solr.search.DocListAndSet;
import org.apache.solr.search.QueryParsing;
import org.apache.solr.search.SolrIndexSearcher;
import org.apache.solr.servlet.SolrServletRequest;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.hs.core.action.BaseAction;
import com.hs.log.HsLogger;
import com.hs.pre.module.data.FjPreCache;
import com.hs.utils.ParseXml;

public class SortSearchAction  extends BaseAction{
	SolrCore core;
	private static final HsLogger logger = HsLogger.getLogger(SortSearchAction.class.getName());
	static int MAX_RETURN_NUM = 84461;
	
	public void init() throws ServletException {
		 core = SolrCore.getSolrCore();
		 logger.config("init"); 
	}
	
	/**
	 * 获得所有方剂的分类id
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception { 
		    init();  
		    
		    System.out.println("______**********************---------------");
		    request.setCharacterEncoding("utf-8");
		    String fjIdStr="";
		    if(request.getParameter("sortId")!=null &&!"".equals(request.getParameter("sortId"))){
		    	FjPreCache sortCache = FjPreCache.getInstance();
		    	fjIdStr = sortCache.getPreStrId(new Long(request.getParameter("sortId").toString()));
		    }
		   
		    SolrServletRequest solrReq = new SolrServletRequest(core, request);;
		    SolrQueryResponse solrRsp = new SolrQueryResponse();
		    
			String q = request.getParameter("q");
			String newQ = "";
			if (q != null && !(q = q.trim()).equals(""))
				newQ = "(" + q + ")";
			if (fjIdStr != "") {
				if (!newQ.equals(""))
					newQ += " AND ";
				newQ += "(" + fjIdStr + ")";
			}
		    
		    SolrParams p = solrReq.getParams();		    
		    logger.info("fq is "+p.get("fq")+" fl is "+p.get("fl")+" new Q is "+newQ);
		    DocListAndSet results = new DocListAndSet();
		    Query query = QueryParsing.parseQuery(newQ, "", p,solrReq.getSchema());
		    SolrIndexSearcher s = solrReq.getSearcher();
			results.docList = s.getDocList(query, null, null, p.getInt(START, 0), p
					.getInt(ROWS, MAX_RETURN_NUM), 0);
			solrRsp.add("results", results.docList);
			
			StringWriter out = new StringWriter();
		    XMLWriter.writeResponse(out,solrReq, solrRsp); 
		    ParseXml parse = new ParseXml(out.getBuffer().toString());
		    List docList = parse.getDoc();
		    
		    //result fangji ids
		    String[] fjIds=new String[docList.size()];
		    for(int i = 0;i<docList.size();i++){
	        	Map docMap = (Map)docList.get(i);
	        	fjIds[i] = docMap.get("id").toString();
	        } 
		    
		    FjPreCache fjPreCache = FjPreCache.getInstance();
		    List list = fjPreCache.findSort(fjIds);
		    request.setAttribute("list", list);
		    logger.info("___查询结束------记录条数:"+docList.size());
		    logger.info("___查询结果_____分类个数:"+list.size());
		    //...go on
		    
			return mapping.findForward("result");
	}
	
	 final void sendErr(int rc, String msg, HttpServletRequest request, HttpServletResponse response) {
		    try {
		      try{
		        response.setContentType(QueryResponseWriter.CONTENT_TYPE_TEXT_UTF8);
		      } catch (Exception e) {}
		      try{response.setStatus(rc);} catch (Exception e) {}
		      PrintWriter writer = response.getWriter();
		      writer.write(msg);
		    } catch (IOException e) {
		       e.printStackTrace();
		    }
		  }
}
